// pages/push/deal/index.js
import wxRequest from '../../../utils/wxRequest.js';
import utils from '../../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0, //当前页面的id
    btn:'更新',
    group_array: [], //站点类型
    group_index: 0,
    items: [ //设备选择
      {
        name: '1',
        value: '不限制',
        checked: 'true'
      },
      {
        name: '2',
        value: '仅移动访问'
      },
      {
        name: '3',
        value: '仅PC访问'
      }
    ],
    areas: [{
      name: '1',
      value: '关闭',
      checked: 'true'
    }],
    agents: [], //投放地区过滤
    agentStr: '', //投放地区的值
    times: [], //投放时间
    times_select_all: false,
    status_array: [{
        id: 1,
        name: '跳转',
      },
      {
        id: 2,
        name: '不跳转'
      }
    ], //是否跳转
    status_index: 0,
    module_array: [], //推广模板
    module_index: 0,
    verify_array: [], //审核页
    verify_index: 0,
    wechat_list: [], //微信分组列表
    obj: {
      wechat_list: []
    }, //存储请求的部分参数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setData({
      id: options.id
    });
    if (options.id <= 0) {
      wx.setNavigationBarTitle({
        title: '添加计划'
      });
      that.setData({btn:'添加'});
    }
    that.getCanshu(that.getDetails);
  },
  //arr初始数组,key键,value值，返回下标
  getIndex(arr, key, value) {
    var res = 0;
    for (var k in arr) {
      if (arr[k][key] == value) {
        res = k;
      }
    }
    return res;
  },
  isShow(arr, str) { //判断是否存在数组中，注意str数据类型
    var res = false;
    res = arr.indexOf(str) > -1 ? true : false;
    return res;
  },
  showAll(initArr, eqArr) { //微信分组全选
    var res = true;
    for (var n = 0; n < initArr.length; n++) {
      var item = (initArr[n].id).toString();
      if (eqArr.indexOf(item) < 0) {
        res = false;
      }
    }
    return res;
  },
  titleFn(e) {
    var that = this;
    that.data.obj['title'] = e.detail.value;
    that.setData({
      obj: that.data.obj
    });
  },
  directoryFn(e) {
    var that = this;
    that.data.obj['directory'] = e.detail.value;
    that.setData({
      obj: that.data.obj
    });
  },
  sourceFn(e) {
    var that = this;
    that.data.obj['source'] = e.detail.value;
    that.setData({
      obj: that.data.obj
    });
  },
  ipsFn(e) {
    var that = this;
    that.data.obj['ips'] = e.detail.value;
    that.setData({
      obj: that.data.obj
    });
  },
  //获取基本参数
  getCanshu(fn) {
    wxRequest.getRequest('/toolkit/plan/create').then(res => {
      this.setData({
        times: res.data.time_list, //投放时间
        agents: res.data.user_agent_list, //UserAgent限制
        wechat_list: res.data.wechat_list, //微信分组列表
        group_array: res.data.sites_list, //站点列表
        module_array: res.data.user_template, //推广模板列表
        verify_array: res.data.user_template, //审核页列表
      })

      if (typeof(fn) == 'function' && this.data.id > 0) {
        fn();
      }
    }).catch(error => {})
  },
  getDetails() { //获取当前计划的内容
    var that = this;
    wxRequest.getRequest('/toolkit/plan/edit', {
      id: that.data.id
    }).then(res => {
      console.log(res)
      that.setData({
        obj: { //显示的参数
          title: res.data.title,
          directory: res.data.directory,
          launchtime: res.data.launchtime ? res.data.launchtime.split(',') : [],
          channel: res.data.channel ? res.data.channel.split(',') : [],
          wechat_list: res.data.wechat_list ? res.data.wechat_list.split(',') : [],
          source: res.data.source,
          ips: res.data.ips,
          station_type: res.data.station_type,
          go_to_type: res.data.go_to_type,
          sh_template: res.data.sh_template,
          template_id: res.data.template_id
        },
        status_index: that.getIndex(that.data.status_array, 'id', res.data.go_to_type), //跳转
        module_index: that.getIndex(that.data.module_array, 'id', res.data.template_id), //模板
        verify_index: that.getIndex(that.data.verify_array, 'id', res.data.sh_template), //审核
        group_index: that.getIndex(that.data.group_array, 'id', res.data.station_type.toString()), //站点类型
      })
      var device_index = that.getIndex(that.data.items, 'name', res.data.device_type);
      if (device_index != 0) { //设备
        that.data.items[0].checked = false;
        that.data.items[device_index].checked = true;
      }

      for (let i = 0; i < that.data.agents.length; i++) { //userAgent
        var re = that.isShow(that.data.obj['channel'], that.data.agents[i].user_agent);
        if (re) {
          that.data.agents[i].checked = true;
        } else {
          that.data.agents[i].checked = false;
        }
      }
      that.setData({
        items: that.data.items,
        agents: that.data.agents,
        agentStr: res.data.channel,
      })
      for (let i = 0; i < that.data.times.length; i++) { //时间
        var re = that.isShow(that.data.obj['launchtime'], that.data.times[i].id);
        if (re) {
          that.data.times[i].checked = true;
        } else {
          that.data.times[i].checked = false;
        }
      }
      that.setData({
        times: that.data.times,
      })
      for (let i = 0; i < that.data.wechat_list.length; i++) { //微信分组
        for (let n = 0; n < that.data.wechat_list[i]['wechat'].length; n++) {
          var id = that.data.wechat_list[i]['wechat'][n].id;
          var re = that.isShow(that.data.obj['wechat_list'], id.toString());
          if (re) {
            that.data.wechat_list[i]['wechat'][n].checked = true;
          } else {
            that.data.wechat_list[i]['wechat'][n].checked = false;
          }
        }
        var bol = that.showAll(that.data.wechat_list[i]['wechat'], that.data.obj['wechat_list']); //判断是否全选
        if (bol) {
          that.data.wechat_list[i].checked = true;
        } else {
          that.data.wechat_list[i].checked = false;
        }
      }
      that.setData({
        wechat_list: that.data.wechat_list,
      })


    }).catch(error => {})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  // 选择站点类型
  bindPickerChange: function(e) {
    var index = e.detail.value;
    this.data.obj['station_type'] = this.data.group_array[index].id;
    this.setData({
      group_index: index,
      obj: this.data.obj
    })
  },
  //UserAgent限制
  checkboxChange(e) {
    var str = e.detail.value.join(',');
    this.data.obj['channel'] = str;
    this.setData({
      agentStr: str,
      obj: this.data.obj
    });
  },
  //投放时间
  timesChange(e) {
    var that = this;
    var len = e.detail.value.length;
    that.setData({
      times: that.data.times
    });
    if (len > 0 && that.data.times_select_all) {
      that.setData({
        times_select_all: false
      });
    }
    if (len == that.data.times.length) {
      that.setData({
        times_select_all: true
      });
    }
    that.data.obj['launchtime'] = e.detail.value;
    that.setData({
      obj: that.data.obj
    });
  },
  timeFn(e) { //单独的时间复选框
    var that = this;
    var index = e.currentTarget.dataset.index;
    var checks = that.data.times[index].checked;
    if (that.data.obj['launchtime']) {
      var idx = that.data.obj['launchtime'].indexOf(that.data.times[index].id);
      if (checks) {
        if (idx > -1) {
          that.data.obj['launchtime'].splice(idx, 1);
        }
      } else {
        if (idx < 0) {
          that.data.obj['launchtime'].push(that.data.times[index].id);
        }
      }
    }
    if (checks) {
      that.data.times[index].checked = false;
    } else {
      that.data.times[index].checked = true;
    }
    that.setData({
      times: that.data.times,
      obj: that.data.obj
    })

  },
  itemFn(e) { //单选微信号复选框
    var that = this;
    var index = e.currentTarget.dataset.idx;
    var index2 = e.currentTarget.dataset.idx2;
    var str = `wechat_list[${index}].wechat[${index2}].checked`;
    var id = that.data.wechat_list[index].wechat[index2].id.toString();
    var checks = that.data.wechat_list[index].wechat[index2].checked;
    that.data.obj['wechat_list'] = that.data.obj['wechat_list'] ? that.data.obj['wechat_list'] : [];
    if (checks && that.data.obj['wechat_list'].indexOf(id) > -1) {
      that.data.obj['wechat_list'].splice(that.data.obj['wechat_list'].indexOf(id), 1);
    } else if (that.data.obj['wechat_list'].indexOf(id) < 0) {
      that.data.obj['wechat_list'].push(id);
    }
    that.setData({
      obj: that.data.obj,
      [str]: !checks
    });
  },
  //选择推广微信号
  groupChange(e) {
    var that = this;
    var index = e.currentTarget.dataset.idx;
    var item = that.data.wechat_list[index]['wechat'];
    var arr = e.detail.value;
    var str = `wechat_list[${index}].checked`;
    that.setData({
      obj: that.data.obj
    });
    if (arr.length >= 0) {
      that.setData({
        [str]: false
      })
    }
    if (arr.length == item.length) {
      that.setData({
        [str]: true
      })
    }

  },
  //选择是否跳转
  statusChange: function(e) {
    var index = e.detail.value;
    this.data.obj['go_to_type'] = this.data.status_array[index].id;
    this.setData({
      obj: this.data.obj,
      status_index: index
    })
  },
  //选择推广模板
  moduleChange: function(e) {
    var index = e.detail.value;
    this.data.obj['template_id'] = this.data.module_array[index].id;
    this.setData({
      obj: this.data.obj,
      module_index: index
    })
  },
  //审核页
  verifyChange: function(e) {
    var index = e.detail.value;
    this.data.obj['sh_template'] = this.data.verify_array[index].id;
    this.setData({
      verify_index: index,
      obj: this.data.obj
    })
  },
  select_all() { //投放时间全选
    let that = this;
    that.setData({
      times_select_all: !that.data.times_select_all
    });
    let arr = that.data.times;
    if (that.data.times_select_all) {
      let arr2 = [];
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked == true) {
          arr2.push(arr[i]);
        } else {
          arr[i].checked = true;
          arr2.push(arr[i]);
        }
      }
      that.setData({
        times: arr2
      })
    } else {
      let arr2 = [];
      for (let i = 0; i < arr.length; i++) {
        arr[i].checked = false;
        arr2.push(arr[i]);
      }
      that.setData({
        times: arr2
      })
    }

  },
  all_group(e) { //微信分组全选
    var that = this;
    var index = e.currentTarget.dataset.idx;
    var checks = that.data.wechat_list[index].checked;
    that.data.wechat_list[index]['checked'] = !checks;
    let arr = that.data.wechat_list[index]['wechat'];
    if (checks) {
      for (let i = 0; i < arr.length; i++) {
        var id = arr[i].id.toString();
        arr[i].checked = false;
        if (that.data.obj['wechat_list'].indexOf(id) > -1) {
          that.data.obj['wechat_list'].splice(that.data.obj['wechat_list'].indexOf(id), 1);
        }
      }
    } else {
      for (let i = 0; i < arr.length; i++) {
        var id = arr[i].id.toString();
        arr[i].checked = true;
        if (that.data.obj['wechat_list'].indexOf(id) < 0) {
          that.data.obj['wechat_list'].push(id);
        }
      }
    }
    that.setData({
      wechat_list: that.data.wechat_list,
      obj: that.data.obj
    });
  },
  submitFn(e) { //提交表单
    var that = this;
    that.data.obj['id'] = that.data.id;
    if (!that.data.obj['station_type']) {
      that.data.obj['station_type'] = that.data.group_array[0].id;
    }
    if (!that.data.obj['go_to_type']) {
      that.data.obj['go_to_type'] = that.data.status_array[0].id;
    }
    if (!that.data.obj['template_id']) {
      that.data.obj['template_id'] = that.data.module_array[0].id;
    }
    if (!that.data.obj['sh_template']) {
      that.data.obj['sh_template'] = that.data.verify_array[0].id;
    }
    if (!that.data.obj['title'].trim()) {
      return wx.showToast({
        title: '计划名称不能为空',
        icon: 'none'
      })
    }
    if (!that.data.obj['directory'].trim()) {
      return wx.showToast({
        title: '目录或渠道名不能为空',
        icon: 'none'
      })
    }
    if (!that.data.obj['launchtime']) {
      return wx.showToast({
        title: '请选择投放时间',
        icon: 'none'
      })
    }
    if (!that.data.obj['wechat_list']) {
      return wx.showToast({
        title: '请选择推广的微信号',
        icon: 'none'
      })
    }
    that.setData({
      obj: that.data.obj
    });
    var obj = { ...e.detail.value,
      ...that.data.obj
    };
    wxRequest.getRequest('/toolkit/plan/save', obj).then(res => {
      that.setData({
        obj: {}
      });
      wx.showToast({
        title: res.message,
        icon: res.code == 0 ? 'success' : 'none',
      })
      if (res.code == 0) {
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/advert/list/index',
          })
        }, 400)

      }

    }).catch(error => {})
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    that.getCanshu(that.getDetails);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

})